package com.itheima.comment.service.impl;

import com.itheima.comment.document.Comment;
import com.itheima.comment.document.CommentLike;
import com.itheima.comment.dto.CommentLikeDto;
import com.itheima.comment.dto.CommentSaveDto;
import com.itheima.comment.reposttory.CommentRepository;
import com.itheima.comment.service.CommentService;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.comment.service.impl
 */
@Slf4j
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 发表评论
     *
     * @param dto
     */
    @Override
    public void save(CommentSaveDto dto) {
        //1. 判断是否为匿名
        if(RequestContextUtil.isAnonymous()){
            throw new LeadNewsException(HttpCodeEnum.NEED_LOGIN);
        }
        //2. 构建Pojo
        int loginUserId = Integer.parseInt(RequestContextUtil.getLoginUserId());
        Comment comment = new Comment();
        BeanUtils.copyProperties(dto,comment);
        comment.setLikes(0);
        comment.setReplys(0);
        comment.setCreatedTime(LocalDateTime.now());
        comment.setUserId(loginUserId);
        comment.setCreatedTime(LocalDateTime.now());
        comment.setUpdatedTime(LocalDateTime.now());

        // 防止中文乱码
        String headImage = RequestContextUtil.getHeader(SystemConstants.LOGIN_USER_IMAGE);
        String nickName = RequestContextUtil.getHeader(SystemConstants.LOGIN_USER_NAME);

        try {
             headImage = URLDecoder.decode(headImage, StandardCharsets.UTF_8.toString());
             nickName = URLDecoder.decode(nickName, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        comment.setHeadImage(headImage);
        comment.setNickName(nickName);

        log.info("往MongoDB保存数据日志打印==>comment:{}", comment);
        //3. 保存
        commentRepository.save(comment);
    }

    /**
     * 评论 点赞或取消点赞
     *
     * @param dto
     */
    @Override
    public void like(CommentLikeDto dto) {
        //1. 判断是否为匿名
        if(RequestContextUtil.isAnonymous()){
            throw new LeadNewsException(HttpCodeEnum.NEED_LOGIN);
        }
        int loginUserId = Integer.parseInt(RequestContextUtil.getLoginUserId());
        //2. 查询点赞记录是否存在
        Query query = new Query(Criteria.where("userId").is(loginUserId)
                .and("commentId").is(dto.getCommentId()));
        CommentLike commentLike = mongoTemplate.findOne(query, CommentLike.class);
        int updateCount = 0;
        //3. 判断点赞类型
        if(dto.getOperation() == 1){
            //3.1 点赞
            // 如果存在则报错，说明点赞过了，不能重复点赞
            if(null != commentLike){
                throw new LeadNewsException("已经点过赞了!");
            }
            // 否则，添加点赞记录
            commentLike = new CommentLike();
            commentLike.setCommentId(dto.getCommentId());
            commentLike.setUserId(loginUserId);
            mongoTemplate.insert(commentLike);
            // 点赞数要+1
            updateCount = 1;
        }else{
            //3.2 取消点赞
            if(null == commentLike){
                // 如果不存在记录则报错
                throw new LeadNewsException("您还没点赞!");
            }
            // 存在则删除点赞记录
            mongoTemplate.remove(query, CommentLike.class);
            // 点赞数要-1
            updateCount = -1;
        }
        //4 更新评论中的赞数量
        Query updateQuery = new Query(Criteria.where("id").is(dto.getCommentId()));
        Update update = new Update();
        update.inc("likes", updateCount);
        mongoTemplate.findAndModify(updateQuery, update, Comment.class);
    }
}